<?php
defined('BASEPATH') OR exit('No direct script access allowed');
?>
<!--返回错误信息-->
<?php echo validation_errors(); ?>
<!DOCTYPE html>
<html lang="en">

<head>
    <?php
$title = [
	'title' => '库存管理-库存查询',
];
$this->load->view('/admin/common/header', $title);
?>
</head>

<body data-type="widgets">
<script src="/assets/js/theme.js"></script>
<div class="am-g tpl-g">

<!--    头部   侧边菜单-->
    <?php $this->load->view('/admin/common/bodyLeft');?>
    <script type="text/javascript">
    	$(".js-sidebar-nav>li:nth-child(10)>ul").show(80);
    	$(".js-sidebar-nav>li:nth-child(10)>a>span").addClass("sidebar-nav-sub-ico-rotate");
    	$(".js-sidebar-nav>li:nth-child(10)>ul>li:nth-child(1)>a").addClass("active");
    </script>
    <!-- 内容区域 -->
    <div class="tpl-content-wrapper">
        <div class="row-content am-cf">
            <div class="row">
                <div class="am-u-sm-12 am-u-md-12 am-u-lg-12">
                    <div class="widget am-cf">
                        <div class="widget-head am-cf">
                            <div class="widget-title  am-cf">库存查询</div>
                        </div>
                        <form action="/admin/goods/remove" id="form_admin" method="post">

                        <div class="widget-body  am-fr">
                            <div class="am-u-md-12 ">
                                <div class="am-u-md-1 am-u-lg-1">
                                    <label class=" col-sm-centered am-md-text-right am-padding-left-0">商品分类</label>
                                </div>
                                <div class="am-u-md-2 am-u-lg-2">
                                    <div class="am-form-group tpl-table-list-select">
                                        <select data-am-selected="{btnSize: 'sm',btnWidth: '100%'}" id="firstClassify" class="unlock">
                                            <option value=""></option>
                                            <option value="2">物料包</option>
                                            <option value="3">书籍</option>
                                            <option value="4">机器耗材</option>
                                            <option value="8">供应商商品</option>
                                            <option value="9">打印机租赁</option>
                                        </select>
                                    </div>
                                </div>
                                <div class="am-u-md-2 am-u-lg-2">
                                    <div class="am-form-group tpl-table-list-select">
                                        <select data-am-selected="{btnSize: 'sm',btnWidth: '100%'}" id="secondClassify">
                                            <option value=""></option>
                                        </select>
                                    </div>
                                </div>
                                <div class=" am-u-md-2 am-u-lg-2">
                                    <div class="am-form-group tpl-table-list-select">
                                        <select data-am-selected="{btnSize: 'sm',btnWidth: '100%'}" id="thirdClassify">
                                            <option value=""></option>
                                        </select>
                                    </div>
                                </div>
                                <div class=" am-u-md-4 am-u-lg-3">
                                    <div class="am-form-group am-input-group am-input-group-sm tpl-form-border-form cl-p">
    <!--                                    <form action="/admin/user/search" method="get">-->
                                        <input type="text" class="am-form-field" name="search" id="searchValue" placeholder="请输入商品名称">
                                        <span class="am-input-group-btn">
                                            <a href="javascript:void(0);" class="am-btn  am-btn-default am-btn-success tpl-table-list-field am-icon-search" id="search">搜索</a>
                                        </span>
    <!--                                    </form>-->
                                    </div>
                                </div>

                            </div>
                            <div class="am-u-sm-12">
                                <div class="am-form-group">
                                    <div class="am-btn-toolbar">
                                        <div class="am-btn-group am-btn-group-xs">
                                            <a href="javascript:void(0);" onclick="" class="am-btn am-btn-primary"><span class="am-icon-download"></span> 导出</a>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="am-u-sm-12">
                                <table width="100%" class="am-table am-table-compact am-table-striped tpl-table-black "
                                       id="example-r">
                                    <thead>
                                    <tr>
                                        <th style="width: 5%"><input type="checkbox" class="checkall" id="checkallBottom">全选</th>
                                        <th style="width: 5%">序号</th>
                                        <th style="width: 15%">商品编码</th>
                                        <th style="width: 15%">商品名称</th>
                                        <th style="width: 15%">商品规格</th>
                                        <th style="width: 15%">商品来源</th>
                                        <th style="width: 10%">商品分类</th>
                                        <th style="width: 10%">库存</th>
                                    </tr>
                                    </thead>
                                    <tbody class="choose-box">
                                    <?php

//                                    print_r($list);
//                                    die();
if (isset($list) && $list) {
	foreach ($list as $v) {

//                                        print_r($v['one_category']);

//                                        2物料包、3书籍、4机器耗材、9打印机租赁、8供应商商品
		if (isset($v['att'])) {
			for ($i = 0; $i < count($v['att']); $i++) {
				$dataId = isset($v['att'][$i]['id']) ? $v['att'][$i]['id'] : $v['att'][$i]['product_stock_priceId'];
				echo '<tr class="gradeX">
                                            <td>
                                                <label class="am-checkbox-inline">
                                                  <input type="checkbox" value=' . $v['id'] . ' data-id="' . $dataId . '" name="del_id[]" class="checkitem">
                                                </label>
                                             </td>
                                             <td>' . $v['id'] . '</td>';
				if (empty($v['ckId'])) {
					echo '<td><a href="/admin/goods/editView?id=' . $v['id'] . '">' . $v['product_no'] . '</a></td>';
				} else {
					echo '<td>' . $v['product_no'] . '</td>';
				}
				echo '<td>' . $v['name'] . '</td>
                                            <td>' . $v['att'][$i]['specification_group_names'] . '</td>
                                             <td>' . $v['source'] . '</td>';

				switch ($v['one_category']) {
				case 0:
					echo '<td></td>';
					break;
				case 2:
					echo '<td>物料包</td>';
					break;
				case 3:
					echo '<td>书籍</td>';
					break;
				case 4:
					echo '<td>机器耗材</td>';
					break;
				case 8:
					echo '<td>供应商商品</td>';
					break;
				case 9:
					echo '<td>打印机租赁</td>';
					break;

				}
				echo '
                                                <td class="inventory-box">' . $v['att'][$i]['stock'] . '</td><td>
                                                <div class="tpl-table-black-operation">
                                                    </div>
                                                </td>
                                              </tr>';
			}
		} else {
			$v['product_stock_priceId'] = isset($v['product_stock_priceId']) ? $v['product_stock_priceId'] : '';
			$v['stock'] = isset($v['stock']) ? $v['stock'] : '';

			echo '<tr class="gradeX">
                                            <td>
                                                <label class="am-checkbox-inline">
                                                  <input type="checkbox" value=' . $v['id'] . ' data-id="' . $v['product_stock_priceId'] . '" name="del_id[]" class="checkitem">
                                                </label>
                                             </td>
                                             <td>' . $v['id'] . '</td>
                                              <td><a href="/admin/goods/editView?id=' . $v['id'] . '">' . $v['product_no'] . '</a></td>
                                             <td>' . $v['name'] . '</td>
                                             <td>暂无规格</td>
                                            <td>' . $v['source'] . '</td>';

			switch ($v['one_category']) {
			case 0:
				echo '<td></td>';
				break;
			case 2:
				echo '<td>物料包</td>';
				break;
			case 3:
				echo '<td>书籍</td>';
				break;
			case 4:
				echo '<td>机器耗材</td>';
				break;
			case 8:
				echo '<td>供应商商品</td>';
				break;
			case 9:
				echo '<td>打印机租赁</td>';
				break;

			}
			echo '
                                                <td class="inventory-box">' . $v['stock'] . '</td>
                                                <td>
                                                    <div class="tpl-table-black-operation">
                                                        <a href="javascript:;" data-am-modal="{target: \'#change-inventory\', closeViaDimmer: 0, width: 400, height: 250}" data-stock-id="' . $v['ckId'] . '" class="change-one">
                                                            <i class="am-icon-pencil"></i> 修改库存
                                                        </a>
                                                    </div>
                                                </td>
                                              </tr>';

		}

	}

} else {
	echo '';
}
?>
                                    </tbody>
                                </table>
                            </div>
                            <div class="am-u-lg-12">
                                <div class="am-u-sm-centered">
                                    <ul class="am-pagination am-pagination-centered" id="paging">

                                    </ul>
                                </div>
                            </div>
                        </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
</div>
<!-- 模态框 -->
<div class="am-modal am-modal-no-btn" tabindex="-1" id="change-inventory">
    <div class="am-modal-dialog">
        <div class="am-modal-hd">修改库存
            <a href="javascript: void(0)" class="am-close am-close-spin" data-am-modal-close>&times;</a>
        </div>
        <div class="am-modal-bd">
            <form class="am-form am-form-horizontal" style="position: relative;top: 25px;">
                <div class="am-form-group">
                    <label for="inventory-num" class="am-u-sm-3 am-form-label">库存：</label>
                    <div class="am-u-sm-9">
                        <input type="text" id="inventory-num" placeholder="输入将要修改的库存">
                    </div>
                </div>
            </form>
            <div style="position: relative;top: 50px;">
                <button type="button" class="am-btn am-btn-primary am-u-sm-6" id="confirm" data-am-modal-close>确定</button>
                <button type="button" class="am-btn am-btn-danger am-u-sm-6" data-am-modal-close>取消</button>
            </div>
        </div>
    </div>
</div>



<script>
    $('.checkall').click(function(){
        $(".checkitem").prop("checked",this.checked);
    });

    var re = /^[0-9]*$/;

    // 批量修改库存
    $("#change-all").click(function(){
        var checkedOne = $(".checkitem:checked");
        var commodityId = [];
        if(checkedOne.length < 1){
            alert("请勾选商品。");
            return false;
        }else{
            for(var i = 0; i < checkedOne.length; i++){
                commodityId.push(checkedOne.eq(i).data("id"));
            }

            $("#confirm").unbind("click").click(function(){
                var inventoryNumber = $("#inventory-num").val();
                if(!re.test(inventoryNumber)||inventoryNumber.replace(/(^\s*)|(\s*$)/g, "")==""){
                    alert("请输入数字。");
                    return false;
                }else{
                    $.ajax({
                        url:"/admin/stock/edit",
                        data:{
                            id:commodityId,
                            stock:inventoryNumber
                        },
                        type:"post",
                        async:false,
                        success:function(data){
                            console.log(data);
                            checkedOne.parents(".gradeX").find(".inventory-box").text(inventoryNumber);
                            $("#inventory-num").val("");
                        },
                        error:function(error){
                            alert(error);
                        }
                    });
                }
            });
        }
    });

    // 修改单个库存
    $(document).on("click",".change-one",function(){
        var commodityId =[];
        commodityId.push($(this).parents(".gradeX").find(".checkitem").data("id"));
        console.log(commodityId)
        var inventoryBox = $(this).parents(".gradeX").find(".inventory-box");
        $("#confirm").unbind("click").click(function(){
            var inventoryNumber = $("#inventory-num").val();
            //判断输入为数字且不为空
            if(!re.test(inventoryNumber)||inventoryNumber.replace(/(^\s*)|(\s*$)/g, "")==""){
                alert("请输入数字。");
                return false;
            }else{
                $.ajax({
                    url:"/admin/stock/edit",
                    data:{
                        id:commodityId,
                        stock:inventoryNumber
                    },
                    type:"post",
                    async:false,
                    success:function(data){
                        inventoryBox.text(inventoryNumber);
                        $("#inventory-num").val("");
                    },
                    error:function(error){
                        alert(error);
                    }

                });

            }
        });
    });

    var oneCategory,
        twoCategory,
        threeCategory,
        search,
        page;

    $("#search").on("click",function(){

        oneCategory = $("#firstClassify").val();
        twoCategory = $("#secondClassify").val();
        threeCategory = $("#thirdClassify").val();
        search = $("#searchValue").val();
        page = 1;

        chooseStock(oneCategory,twoCategory,threeCategory,search,page);

    });

    //商品分类,级联菜单  及  筛选商品
    selectChange("#firstClassify","#secondClassify","/api/goods/twoCategory","one");
    selectChange("#secondClassify","#thirdClassify","/api/goods/threeCategory","two");
    selectChange("#thirdClassify","","","");

    //商品分类,级联菜单  及  筛选商品
    function selectChange(changeId,nextSelect,url,changeNum){
        $(document).on("change" , changeId + ".unlock" , function() {

            //有这个class时，移除，不走下面代码
            if($(changeId).hasClass("noAjax")){
                $(changeId).removeClass("noAjax");
                return false;
            }

            if(changeId == "#thirdClassify"){
                //筛选商品
                oneCategory = $("#firstClassify").val();
                twoCategory = $("#secondClassify").val();
                threeCategory = $("#thirdClassify").val();
                search = $("#searchValue").val();
                page = 1;

                chooseStock(oneCategory,twoCategory,threeCategory,search,page);
                return false;
            }

            //级联菜单
            var categoryValue = $(changeId).val();
            var data = changeNum + "Category=" + categoryValue;
            var option = "<option value=''><optian>";

            $.ajax({
                type: "POST",
                url : url,
                data: data,
                dataType: "json",
                success: function(data){
                    console.log(data)
                    for(var i = 0; i<data.length; i++){
                        if(data[i].product_categoryId){
                            option += '<option value="'+ data[i].product_categoryId +'">'+ data[i].name +'</option>';

                        }else{
                            option += '<option value="'+ data[i].id +'">'+ data[i].name +'</option>';
                        }
                    }
                    $(nextSelect).removeClass("unlock");
                    $(nextSelect).html(option);

                    setTimeout(function() {
                        $(nextSelect).addClass("unlock");
                    }, 0);

                    // 在第三个分类有option前提下，换第一个分类，给第三个分类清空，会触发change事件，加class，让第三个分类有class时候不请求ajax
                    if(changeId == "#firstClassify" && $("#thirdClassify option").length != 1){
                        $("#thirdClassify").empty().addClass("noAjax");
                    }
                },
                complete:function() {
                    //筛选商品
                    oneCategory = $("#firstClassify").val();
                    twoCategory = $("#secondClassify").val();
                    threeCategory = $("#thirdClassify").val();
                    search = $("#searchValue").val();
                    page = 1;

                    chooseStock(oneCategory,twoCategory,threeCategory,search,page);

                },
                error: function (data) {
                    // alert(XMLHttpRequest.status);
                    // alert(XMLHttpRequest.readyState);
                    // alert(textStatus);
                }
            });


        });
    }

    function chooseStock(oneCategory,twoCategory,threeCategory,search,page){
        $.ajax({
            type: "GET",
            url : "/api/stock/search",
            data: {
                oneCategory: oneCategory,
                twoCategory: twoCategory,
                threeCategory: threeCategory,
                search: search,
                page: page
            },
            dataType: "json",
            beforeSend:function(){
                $(".my-dark").css("display","block");
            },
            success: function(msg){
                var data = msg['0'];
                var list,
                    dataId,
                    category,
                    lianjie,
                    productStockPriceId,
                    stock;
                if(!data[0]){
                    list += '<tr class="gradeX"><td colspan="9">暂无数据</td></tr>'
                }else{
                    for(var i = 0 ; i < data.length; i++){

                        category = data[i].one_category == 0 ? "" :
                                    data[i].one_category == 2 ? "物料包" :
                                        data[i].one_category == 3 ? "书籍" :
                                            data[i].one_category == 4 ? "机器耗材" :
                                                data[i].one_category == 8 ? "供应商商品" : "打印机租赁";
                        if(data[i].att){
                            for(var j = 0 ; j < data[i].att.length; j++){
                                dataId = data[i].att[j].id ? data[i].att[j].id : data[i].att[j].product_stock_priceId;
                                lianjie = data[i].ckId ? data[i].product_no : '<a href="/admin/goods/editView?id='+ data[i].id +'">'+ data[i].product_no +'</a>';
                                list += '<tr class="gradeX">'
                                        + '<td>'
                                            + '<label class="am-checkbox-inline">'
                                                + '<input type="checkbox" value='+ data[i].id +' data-id="'+ dataId +'" name="del_id[]" class="checkitem">'
                                            + '</label>'
                                        + '</td>'
                                        + '<td>'+ data[i].id +'</td>'
                                        + '<td>'+ lianjie +'</td>'
                                        + '<td>'+ data[i].name +'</td>'
                                        + '<td>'+ data[i].att[j].specification_group_names +'</td>'
                                        + '<td>'+ data[i].source +'</td>'
                                        + '<td>'+ category +'</td>'
                                        + '<td class="inventory-box">'+ data[i].att[j].stock +'</td>'
                                        + '<td>'
                                            + '<div class="tpl-table-black-operation">'
                                                + '<a href="javascript:;" data-am-modal="{target: \'#change-inventory\', closeViaDimmer: 0, width: 400, height: 250}" data-stock-id="'+ dataId +'" class="change-one">'
                                                    + '<i class="am-icon-pencil"></i> 修改库存'
                                                + '</a>'
                                            + '</div>'
                                        + '</td>'
                                     + '</tr>'
                            }
                        }else{
                            productStockPriceId = data[i].product_stock_priceId ? data[i].product_stock_priceId : "";
                            stock = data[i].stock ? data[i].stock : "";

                            list += '<tr class="gradeX">'
                                    + '<td>'
                                        + '<label class="am-checkbox-inline">'
                                            + '<input type="checkbox" value='+ data[i].id +' data-id="'+ productStockPriceId +'" name="del_id[]" class="checkitem">'
                                        + '</label>'
                                    + '</td>'
                                    + '<td>'+ data[i].id +'</td>'
                                    + '<td>'+ lianjie +'</td>'
                                    + '<td>'+ data[i].name +'</td>'
                                    + '<td>暂无规格</td>'
                                    + '<td>'+ data[i].source +'</td>'
                                    + '<td>'+ category +'</td>'
                                    + '<td class="inventory-box">'+ stock +'</td>'
                                    + '<td>'
                                        + '<div class="tpl-table-black-operation">'
                                            + '<a href="javascript:;" data-am-modal="{target: \'#change-inventory\', closeViaDimmer: 0, width: 400, height: 250}" data-stock-id="'+ dataId +'" class="change-one">'
                                                + '<i class="am-icon-pencil"></i> 修改库存'
                                            + '</a>'
                                        + '</div>'
                                    + '</td>'
                                 + '</tr>'

                        }

                    }

                }
                $(".choose-box").html(list);

                //分页
                //设置分页信息
                var pageOptions = {
                    AllowPaging: true,
                    PageIndex: msg.this_page,      //设置当前页码
                    PageSize: msg.pageNum,       //设置分页大小
                    RecordCount: msg.total_num,  //设置数据总数
                    // TotalPage: ,      //设置总页数
                    showPageCount: 4,
                    onPageClick: function(pageIndex) {
                        chooseStock(oneCategory,twoCategory,threeCategory,search,pageIndex);
                    }
                }
                //初始化分页栏
                $('#paging').pageBar(pageOptions);

            },
            complete:function(){
                $(".my-dark").css("display","none");
            },
            error: function (data) {
               //  alert(XMLHttpRequest.status);
               //  alert(XMLHttpRequest.readyState);
               //  alert(textStatus);
            }
        });
    }

</script>

<script src="/assets/js/amazeui.min.js"></script>
<script src="/assets/js/amazeui.datatables.min.js"></script>
<script src="/assets/js/dataTables.responsive.min.js"></script>
<script src="/assets/js/app.js"></script>
<script src="/assets/js/page.js"></script>
<script>
    $(document).ready(function() {
        //设置分页信息
        var pageOptions = {
            AllowPaging: true,
            PageIndex: <?php echo $_GET['page'] ?>,      //设置当前页码
            PageSize: <?php echo $pageNum ?>,       //设置分页大小
            RecordCount: <?php echo $totalNum ?>,  //设置数据总数
            // TotalPage: ,      //设置总页数
            showPageCount: 4,
            onPageClick: function(pageIndex) {
                var search = '<?php echo isset($_GET['search']) ? $_GET['search'] : 0 ?>';
                var page = parseInt(pageIndex);
                if(search){
                    window.location.href = "?page="+ page + "&search=" + search;
                }else {
                    window.location.href = "?page="+ page;
                }

            }
        }
        //初始化分页栏
        $('#paging').pageBar(pageOptions);
    })
</script>
</body>

</html>